package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
@EnableTransactionManagement
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    UserService userService;
    @Autowired
    AddressBookService addressBookService;

    @Override
    @Transactional
    public void submit(Long userId, Orders order) {
        order.setUserId(userId);
        //保存订单明细
        //获取当前用户订单购物车向平
        LambdaQueryWrapper <ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        if (shoppingCarts==null||shoppingCarts.size()==0){
            throw new CustomException("购物车为空，不能下单");
        }
        //查询用户信息
        User user = userService.getById(userId);
        order.setPhone(user.getPhone());
        order.setUserName(user.getName());

        //地址信息
        AddressBook addressBook = addressBookService.getById(order.getAddressBookId());
        if(addressBook==null){
            throw new CustomException("地址有误，不能下单");
        }
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());

        //计算总价钱
        //保存订单细节
        Long orderId = IdWorker.getId();
        order.setNumber(orderId+"");
        AtomicInteger amount = new AtomicInteger(0);
        shoppingCarts.forEach(item -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
//            orderDetail.setName(user.getName());
//            orderDetail.setAmount(item.getAmount());
//            orderDetail.setDishId(item.getDishId());
//            orderDetail.setDishFlavor(item.getDishFlavor());
//            orderDetail.setImage(item.getImage());
            BeanUtils.copyProperties(item,orderDetail);
            orderDetailService.save(orderDetail);
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());

        });
        order.setAmount(new BigDecimal(amount.get()));
        //待付款
        order.setStatus(1);
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        //保存订单
        this.save(order);
        //清空购物车
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
    }

    @Override
    public R<Page> userPage(int page, int pageSize) {
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Orders::getCheckoutTime);
        this.page(ordersPage,queryWrapper);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        List<Orders> records = ordersPage.getRecords();

        List <OrdersDto> ordersDtoList = records.stream().map(item -> {
            Long userId = item.getUserId();
            User user = userService.getById(userId);
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            ordersDto.setPhone(user.getPhone());
            AddressBook addressBook = addressBookService.getById(item.getAddressBookId());
            ordersDto.setConsignee(addressBook.getConsignee());
            ordersDto.setAddress(addressBook.getDetail());
            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderDetail::getOrderId,item.getNumber());
            List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper1);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());

        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);
    }

}
